package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.dto.CartResponseDTO;
import cn.edu.tju.elm.mapper.CartMapper;
import cn.edu.tju.elm.model.Cart;
//import cn.edu.tju.elb.service.CartItemService;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.core.security.PermissionUtils;
import cn.edu.tju.elm.service.CartService;
import cn.edu.tju.elm.service.FoodService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/carts")
@Tag(name = "管理购物车", description = "对购物车内的商品增删改查")
public class CartController {
    @Autowired
    private UserService userService;

//    @Autowired
//    private CartItemService cartItemService;

    @Autowired
    private CartService cartService;

    @Autowired
    private FoodService foodService;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private PermissionUtils permissionUtils;

    @PostMapping()
    @PreAuthorize("hasAnyAuthority('ADMIN','USER')")
    @Operation(summary = "增加购物项")
    public HttpResult<Cart>  addCartItem(@RequestBody Cart cart){
        try {
            User user = userService.getUserWithAuthorities().get();
            Long foodId = cart.getFood().getId();
            cart.setBusiness(foodService.getBusinessByFoodId(foodId));
            cart.setCustomer(user);
            LocalDateTime now = LocalDateTime.now();
            cart.setCreator(user.getId());
            cart.setCreateTime(now);
            cart.setUpdater(user.getId());
            cart.setUpdateTime(now);
            cart.setDeleted(false);
            Cart c = cartService.addCartItem(cart);
            return HttpResult.success(c);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "添加购物项失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN') or @permissionUtils.canAccessCartData(#id)")
    @Operation(summary = "查看当前购物车")
    public HttpResult<List<CartResponseDTO>> getCarts(@PathVariable Long id){
        try {
            List<Cart> carts = cartService.getCartsByUserId(id);
            List<CartResponseDTO> responseDTOs = cartMapper.cartsToResponseDTOs(carts);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询购物车失败: " + e.getMessage());
        }
    }

    @GetMapping("/current-user")
    @PreAuthorize("hasAnyAuthority('ADMIN','USER')")
    @Operation(summary = "查看当前用户的购物车")
    public HttpResult<List<CartResponseDTO>> getCurrentUserCarts(){
        try {
            User user = userService.getUserWithAuthorities().get();
            List<Cart> carts = cartService.getCartsByUserId(user.getId());
            List<CartResponseDTO> responseDTOs = cartMapper.cartsToResponseDTOs(carts);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询当前用户购物车失败: " + e.getMessage());
        }
    }

    @GetMapping("/by-business/{businessId}")
    @PreAuthorize("hasAnyAuthority('ADMIN','USER')")
    @Operation(summary = "根据店铺ID查询购物车")
    public HttpResult<List<CartResponseDTO>> getCartsByBusiness(@PathVariable Long businessId){
        try {
            User user = userService.getUserWithAuthorities().get();
            List<Cart> carts = cartService.getCartsByUserIdAndBusinessId(user.getId(), businessId);
            List<CartResponseDTO> responseDTOs = cartMapper.cartsToResponseDTOs(carts);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询店铺购物车失败: " + e.getMessage());
        }
    }

    @GetMapping("/by-food/{foodId}")
    @PreAuthorize("hasAnyAuthority('ADMIN','USER')")
    @Operation(summary = "根据商品ID查询购物车")
    public HttpResult<List<CartResponseDTO>> getCartsByFood(@PathVariable Long foodId){
        try {
            User user = userService.getUserWithAuthorities().get();
            List<Cart> carts = cartService.getCartsByUserIdAndFoodId(user.getId(), foodId);
            List<CartResponseDTO> responseDTOs = cartMapper.cartsToResponseDTOs(carts);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询商品购物车失败: " + e.getMessage());
        }
    }

    @GetMapping("/total-price")
    @PreAuthorize("hasAnyAuthority('ADMIN','USER')")
    @Operation(summary = "计算购物车总价")
    public HttpResult<BigDecimal> getCartTotalPrice(){
        try {
            User user = userService.getUserWithAuthorities().get();
            BigDecimal totalPrice = cartService.calculateTotalPrice(user.getId());
            return HttpResult.success(totalPrice);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "计算购物车总价失败: " + e.getMessage());
        }
    }

    @DeleteMapping()
    @PreAuthorize("hasAnyAuthority('ADMIN','USER')")
    @Operation(summary = "删除购物项")
    public HttpResult<String>  deleteCartItem(@RequestBody Cart cart){
        try {
            cartService.deleteCart(cart.getId());
            return HttpResult.success("删除成功");
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "删除购物项失败: " + e.getMessage());
        }
    }

    @PutMapping()
    @PreAuthorize("hasAnyAuthority('ADMIN','USER')")
    @Operation(summary = "修改购物项")
    public HttpResult<CartResponseDTO>  updateCartItem(@RequestBody Cart cart){
        try {
            User user = userService.getUserWithAuthorities().get();
            cart.setUpdater(user.getId());
            cart.setUpdateTime(LocalDateTime.now());
            Cart updatedCart = cartService.updateCart(cart);
            CartResponseDTO responseDTO = cartMapper.cartToResponseDTO(updatedCart);
            return HttpResult.success(responseDTO);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "修改购物项失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN') or @permissionUtils.canAccessCartData(#id)")
    @Operation(summary = "清空购物车")
    public HttpResult<String>  deleteCarts(@PathVariable Long id){
        try {
            cartService.deleteCartsByUserId(id);
            return HttpResult.success("清空购物车成功");
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "清空购物车失败: " + e.getMessage());
        }
    }

    @PatchMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN') or @permissionUtils.canAccessCartData(@cartService.getCartById(#id).get().getCustomer().getId())")
    @Operation(summary = "部分修改购物车")
    public HttpResult<CartResponseDTO>  partiallyUpdateCart(@PathVariable Long id, @RequestBody Cart cart){
        try {
            User user = userService.getUserWithAuthorities().get();
            Optional<Cart> existingCart = cartService.getCartById(id);
            if (existingCart.isPresent()) {
                Cart cartToUpdate = existingCart.get();
                // 只更新非空字段
                if (cart.getQuantity() != null) {
                    cartToUpdate.setQuantity(cart.getQuantity());
                }
                if (cart.getFood() != null) {
                    cartToUpdate.setFood(cart.getFood());
                }
                if (cart.getCustomer() != null) {
                    cartToUpdate.setCustomer(cart.getCustomer());
                }
                if (cart.getBusiness() != null) {
                    cartToUpdate.setBusiness(cart.getBusiness());
                }
                if (cart.getDeleted() != null) {
                    cartToUpdate.setDeleted(cart.getDeleted());
                }
                cartToUpdate.setUpdater(user.getId());
                cartToUpdate.setUpdateTime(LocalDateTime.now());
                Cart updatedCart = cartService.updateCart(cartToUpdate);
                CartResponseDTO responseDTO = cartMapper.cartToResponseDTO(updatedCart);
                return HttpResult.success(responseDTO);
            } else {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "购物项不存在");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "部分修改购物车失败: " + e.getMessage());
        }
    }
}
